package com.maimao.goods.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.maimao.core.enums.ExceptionEnum;
import com.maimao.core.enums.GoodsStatusEnum;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.exception.MaiMaoException;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.email.EmailSender;
import com.maimao.goods.callback.kafka.callback.PublishCallback;
import com.maimao.goods.client.EsClient;
import com.maimao.goods.client.EsDocClient;
import com.maimao.goods.client.ShopClient;
import com.maimao.goods.mapper.GoodsMapper;
import com.maimao.message.kafka.sender.KafkaSender;
import com.maimao.model.goods.Goods;
import com.maimao.model.goods.enums.GoodsCheckEnum;
import com.maimao.model.goods.log.GoodsCheck;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;

import java.util.List;

import static com.maimao.core.constant.Constants.ONE;

/**
 * @author MaoLin Wang
 * @date 2021/3/25 11:49 下午
 */
@Slf4j
@Service
public class GoodsCheckService {
    @Value("${maimao.kafka.topic.publish}")
    private String publishTopic;
    @Autowired
    private EsClient esClient;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private EmailSender emailSender;

    /**
     * 商品审核邮件发送主题
     */
    @Value("${maimao.mail.goodsCheck.subject}")
    private String subject;

    /**
     * 商品审核邮件发送内容
     */
    @Value("${maimao.mail.goodsCheck.content}")
    private String content;

    @Value("${maimao.mail.goodsCheck.goods_href_ware}")
    private String goodsHrefWare;

    @Value("${maimao.mail.goodsCheck.goods_href}")
    private String goodsHref;

    @Autowired
    private ShopClient shopClient;

    @Resource
    private ThreadPoolTaskExecutor emailSendPool;

    @Autowired
    private KafkaSender kafkaSender;

    @Autowired
    private EsDocClient esDocClient;

    /**
     * 审核商品编辑
     *
     * @param id      审核记录id
     * @param goodsId 商品id
     * @param status  审核结果 1 通过 2未通过
     */
    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void check(String id, String goodsId, Integer status, String failReason) {
        Goods goods = goodsMapper.selectById(Long.valueOf(goodsId));
        GoodsCheck goodsCheck = GoodsCheck.builder()
                .id(id)
                .status(status)
                .failReason(status.equals(GoodsCheckEnum.APPROVED.getCode()) ? null : failReason)
                .checkTime(DateUtils.now()).build();
        if (status.equals(GoodsCheckEnum.APPROVED.getCode()) || status.equals(GoodsCheckEnum.UN_APPROVED.getCode())) {
            //通过 or 不通过
            esClient.updateStatus(goodsCheck);
            goodsMapper.updateByGId(Goods.builder().status(status.equals(GoodsCheckEnum.APPROVED.getCode()) ? GoodsStatusEnum.VALID.getCode() : GoodsStatusEnum.NOT_VALID.getCode()).id(Long.valueOf(goodsId)).build());
            //发送邮件通知
            sendEmail(status, failReason, goods);
            if (status.equals(GoodsCheckEnum.APPROVED.getCode())) {
                //审核通过后发送kafka同步信息
                kafkaSender.sendCallBack(publishTopic, String.valueOf(goods.getId()), String.valueOf(goods.getId()), new PublishCallback(publishTopic, goods.getId(), kafkaSender, esDocClient));
            }

        } else {
            throw new MaiMaoException(ExceptionEnum.GOODS_CHECK_INVALID);
        }
    }

    /**
     * 发送审核结果邮件
     *
     * @param status
     * @param failReason
     * @param goods
     */
    private void sendEmail(Integer status, String failReason, Goods goods) {
        Result<String> emailRes = shopClient.queryUserEmailById(goods.getShopId());

        emailSendPool.execute(() -> {
            if (ObjectUtil.isNotNull(emailRes) && ObjectUtil.isNotNull(emailRes.getData())) {
                log.info("准备发送邮件..........");
                List<Object> params = Lists.newLinkedList();
                //商品商家后台链接
                params.add(goods.getOnSell().equals(ONE) ? goodsHref : goodsHrefWare);
                params.add(goods.getName());
                params.add("red");
                params.add(status.equals(GoodsCheckEnum.APPROVED.getCode()) ? "通过" : "不通过");
                params.add(StringUtils.isNotEmpty(failReason) ? failReason : "无");

                emailSender.sendHtml(subject, emailRes.getData(), StrUtil.format(content, params.toArray()));
            }
        });

    }
}
